layui.define(['layer', 'table','form'], function (exports) {
    var $ = layui.jquery, layer = layui.layer, table = layui.table,form = layui.form;

    var treetable = {
    	
        //线性执行函数
    	exec : $.Deferred(),
    	
    	//缓存数据
    	cache:[],
    	
    	//缓存选中行数据
    	cacheCheckedData:[],
    	
        // 渲染树形表格
        render: function (param) {
        	
        	// 检查参数
            if (!treetable.checkParam(param)) {
            	return; 
            }
            
            // 获取数据
            if (param.data) {
            	
            	_this=treetable.init(param, param.data);
                
            } else {
            	
                $.getJSON(param.url, param.where, function (res) {
                	_this=treetable.init(param, res.data);
                });
            }
            
            return this;
        },
        
        // 渲染表格
        init: function (param, data) {
            var mData = [];
            var doneCallback = param.done;
            var returnback=param.returnback;
            var tNodes = data;
            
            for (var i = 0; i < tNodes.length; i++) {
                var tt = tNodes[i];
                if (!tt.code) {
                    if (!param.treeIdName) {
                        return;
                    }
                    tt.code = tt[param.treeIdName];
                }
                if (!tt.parentCode) {
                    if (!param.treePidName) {
                        return;
                    }
                    tt.parentCode = tt[param.treePidName];
                }
            }

            // 对数据进行排序
            var sort = function (s_pid, data) {
                for (var i = 0; i < data.length; i++) {
                    if (data[i].parentCode == s_pid) {
                        var len = mData.length;
                        if (len > 0 && mData[len - 1].code == s_pid) {
                            mData[len - 1].isParent = true;
                        }
                        mData.push(data[i]);
                        sort(data[i].code, data);
                    }
                }
            };
            sort(param.treeSpid, tNodes);

            // 重写参数
            param.url = undefined;
            param.data = mData;
            treetable.cache=mData;
            param.page = {
                count: param.data.length,
                limit: param.data.length
            };
            
            param.cols[0][param.treeColIndex].templet = function (d) {
                var code = d.code;
                var parentCode = d.parentCode;
                var isDir = d.isParent;
                var indent = treetable.indent(code, mData);
                var iconHtml = '';
                for (var i = 0; i < indent; i++) {
                    iconHtml += '<span style="display: inline-block;width: 20px;"></span>';
                }
                if (isDir) {
                    iconHtml += '<i class="layui-icon layui-icon-triangle-d"></i> <i class="layui-icon layui-icon-layer"></i>';
                } else {
                    iconHtml += '<i class="layui-icon layui-icon-file"></i>';
                }
                iconHtml += '&nbsp;&nbsp;';
                var dataType = isDir ? 'dir' : 'file';
                var text = '<span class="treeTable-icon open" lay-tid="' + code + '" lay-tpid="' + parentCode + '" lay-ttype="' + dataType + '">';
                return text + iconHtml + d[param.cols[0][param.treeColIndex].field] + '</span>'
            };

            param.done = function (res, curr, count) {
                $(param.elem).next().addClass('treeTable').attr('treeLinkage', param.treeLinkage);
                $('.treeTable .layui-table-page').css('display', 'none');
                
                //是否开启展开树功能-->默认不展开
                if (param.treeDefaultClose) { 
                	treetable.foldAll(param.elem); 
                }
                
                //执行layui table中原生回调函数
                if (doneCallback) {
                    doneCallback(res, curr, count);
                }
                
                //判断是否开启单选模式-->单选模式一般用在修改
                var _filter=($(param.elem).prop("lay-filter")?$(param.elem).prop("lay-filter"):param.filter);
                if(param.tree){
	                table.on('checkbox('+_filter+')',function(row){
			            treetable.pchecked(param.elem,row.data.code,row.data.parentCode,row.checked,true);
			            treetable.getData(param.elem);
	        		});
                }else{
                	$('input:checkbox[lay-filter="layTableAllChoose"]').prop("disabled", 'disabled').removeAttr("checked");
                	table.on('checkbox('+_filter+')',function(row){
			            treetable.ochecked(param.elem,row.data.code,row.data.parentCode,row.checked);
			            //TODO  当前这步骤可以省略....
			            if(returnback){
			            	returnback(row.checked?row:null);
			            }
	        		});
                }
                
                //判断是否需要默认选中
                if(param.defaultData && param.defaultData instanceof Function === true) {
                	treetable.defalutData(param.elem,param.defaultData(),true);
                	treetable.getData(param.elem);
	            }
            };

            // 渲染表格
            table.render(param);
            layui.form.render();
        },
        
        // 计算缩进的数量
        indent: function (code, data) {
            var num = 0;
            if (!code) {  return num; }
            var tCode;
            for (var i = 0; i < data.length; i++) {
                if (code == data[i].code) {
                    num += 1;
                    tCode = data[i].parentCode;
                    break;
                }
            }
            return num + treetable.indent(tCode, data);
        },
        
        // 展开/折叠行
        toggleRows: function ($dom, linkage) {
            var type = $dom.attr('lay-ttype');
            if ('file' == type) {  return;  }
            var mId = $dom.attr('lay-tid');
            var isOpen = $dom.hasClass('open');
            if (isOpen) {  $dom.removeClass('open');  } else {
                $dom.addClass('open');
            }
            $dom.closest('tbody').find('tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var pid = $ti.attr('lay-tpid');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if (mId == pid) {
                    if (isOpen) {
                        $(this).hide();
                        if ('dir' == ttype && tOpen == isOpen) {
                            $ti.trigger('click');
                        }
                    } else {
                        $(this).show();
                        if (linkage && 'dir' == ttype && tOpen == isOpen) {
                            $ti.trigger('click');
                        }
                    }
                }
            });
        },
        
        // 检查参数
        checkParam: function (param) {
            if (!param.treeSpid && param.treeSpid != 0) {
                return false;
            }

            if (!param.treeColIndex && param.treeColIndex != 0) {
                return false;
            }
            return true;
        },
        
        // 展开所有
        expandAll: function (dom) {
            $(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if ('dir' == ttype && !tOpen) {
                    $ti.trigger('click');
                }
            });
        },
        
        // 折叠所有
        foldAll: function (dom) {
            $(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if ('dir' == ttype && tOpen) {
                    $ti.trigger('click');
                }
            });
        },
        
        //选中当前，其他不选中
        ochecked: function(dom,tid,tpid,checked){
			$(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function (index,item) {
                var $ti = $(item).find('span[class*="treeTable-icon"]'),_tid = $ti.attr('lay-tid');
                if(tid==_tid){
                	$(item).find("input[type='checkbox']").prop("checked",checked);
					if(checked){
                		$(item).find(".layui-form-checkbox").addClass("layui-form-checked");
                	}else{
                		$(item).find(".layui-form-checkbox").removeClass("layui-form-checked");
                	}
                }else{
                	$(item).find("input[type='checkbox']").prop("checked",false);
                	$(item).find(".layui-form-checkbox").removeClass("layui-form-checked");
                }
            });
        },
        
        //选中子级节点
        pchecked: function(dom,tid,tpid,checked,boo){
			$(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function (index,item) {
                var $ti = $(item).find('span[class*="treeTable-icon"]'),_tpid = $ti.attr('lay-tpid'),_tid=$ti.attr('lay-tid');
                if(tid==_tpid){
                	$(item).find("input[type='checkbox']").prop("checked",checked);
					if(checked){
                		$(item).find(".layui-form-checkbox").addClass("layui-form-checked");
                	}else{
                		$(item).find(".layui-form-checkbox").removeClass("layui-form-checked");
                	}
					treetable.pchecked(dom,_tid,_tpid,checked,false);
                }
            });
			
			if(boo){
            	var count=treetable.tchecked(dom,tid,tpid,checked);
            	treetable.cchecked(dom,tid,tpid,(count>0)?true:false);
            }
        },
       
        //选中父级节点
        cchecked: function(dom,tid,tpid,checked){
       		$(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function (index,item) {
                var $ti = $(item).find('span[class*="treeTable-icon"]'), _tpid=$ti.attr('lay-tpid'), _tid = $ti.attr('lay-tid');
                if(tpid==_tid){
                	$(item).find("input[type='checkbox']").prop("checked",checked);
					if(checked){
                		$(item).find(".layui-form-checkbox").addClass("layui-form-checked");
                	}else{
                		$(item).find(".layui-form-checkbox").removeClass("layui-form-checked");
                	}
                	if(_tid!="-1"){
                		treetable.cchecked(dom,_tid,_tpid,checked);
                	}
                }
    		});
        },
       
        //获取是否有节点选中
        tchecked: function(dom,tid,tpid,checked){
       		let count=0;
       		$(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function (index,item) {
                var $ti = $(item).find('span[class*="treeTable-icon"]'), _tpid=$ti.attr('lay-tpid'), _tid = $ti.attr('lay-tid');
                
                //兄弟元素是否选中
                if(tpid==_tpid){
                	var isChecked=$(item).find("div[class*='layui-form-checkbox']").hasClass("layui-form-checked");
                	if(isChecked){
                		count++;
                	}
                }
				
				//父级元素是否选中
				if(tpid==_tid){
					count+=treetable.tchecked(dom,_tid,_tpid,checked);
					if(count==1 || _tpid=="-1"){
						count=0;
					}
				}
    		});
    		return count;
        },
        
        //获取选中行节点数据
        getData:function(dom){
        	if(!dom){
        		return treetable.cacheCheckedData;
        	}
        	treetable.cacheCheckedData=[];
        	$(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function (index,item) {
        		var isChecked=$(item).find("div[class*='layui-form-checkbox']").hasClass("layui-form-checked");
				if(isChecked){
					var ind=$(item).data("index");
					treetable.cacheCheckedData.push(treetable.cache[ind]);
				}
    		});
        	return treetable.cacheCheckedData;
        },
        
        //获取选中行节点数据
        defalutData:function(dom,data,checked){
        	if(!data){   return false;  }
        	$(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function (index,item) {
                var $ti = $(item).find('span[class*="treeTable-icon"]'),tcode=$ti.attr('lay-tid');
                for(var i=0;i<data.length;i++){
                	if(data[i].code==tcode){
                    	$(item).find("input[type='checkbox']").prop("checked",checked);
    					if(checked){
                    		$(item).find(".layui-form-checkbox").addClass("layui-form-checked");
                    	}else{
                    		$(item).find(".layui-form-checkbox").removeClass("layui-form-checked");
                    	}
                    }
                }
            });
        },
    };

    // 给图标列绑定事件
    $('body').on('click', '.treeTable .treeTable-icon', function () {
        var treeLinkage = $(this).parents('.treeTable').attr('treeLinkage');
        if ('true' == treeLinkage) {
            treetable.toggleRows($(this), true);
        } else {
            treetable.toggleRows($(this), false);
        }
    });

    exports('treetable', treetable);
});
